package job2code.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;
import java.util.Properties;

public class JDBCUtils {

//  连接池引用
    private static DataSource dataSource;
    static {
        try {
//            创建Properties对象
            Properties properties = new Properties();
//            获得db.properties文件的输入流。
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
//            从流中加载配置
            properties.load(Objects.requireNonNull(is));
//            打印配置信息
            System.out.println(properties);
//            根据配置创建Druid连接池
            dataSource = DruidDataSourceFactory.createDataSource(properties);
//            关闭输入流
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    从池中获取连接
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

//    按参数顺序关闭， 参数可以是 Connection、Statement、ResultSet 等类型，因为它们都实现了AutoCloseable接口
    public static void close(AutoCloseable... closeableStreams) throws Exception {
        for (AutoCloseable closeableStream : closeableStreams)
            if (closeableStream != null)
                closeableStream.close();
    }

}
